from loguru import logger
from binance import Client
import pymysql
from env_config import EnvConfig

# 从环境变量获取配置
MYSQL_HOST = EnvConfig.get_mysql_host()
MYSQL_USER = EnvConfig.get_mysql_user()
MYSQL_PSW = EnvConfig.get_mysql_password()
MYSQL_DB = EnvConfig.get_mysql_db()
MYSQL_DB_CACHE = EnvConfig.get_mysql_db_cache()

API_KEY = EnvConfig.get_api_key()
API_SECRET = EnvConfig.get_api_secret()
IS_TESTNET = EnvConfig.get_is_testnet()

SYMBOL = EnvConfig.get_symbol()

client = None
client_anonymous = None


def get_client():
    global client
    if client is None:
        client = Client(API_KEY, API_SECRET, testnet=IS_TESTNET)
    return client


def get_client_anonymous():
    global client_anonymous
    if client_anonymous is None:
        client_anonymous = Client("", "")
    return client_anonymous


def get_db():
    db = pymysql.connect(host=MYSQL_HOST, user=MYSQL_USER, password=MYSQL_PSW, database=MYSQL_DB)
    return db


def get_db_cache():
    db = pymysql.connect(host=MYSQL_HOST, user=MYSQL_USER, password=MYSQL_PSW, database=MYSQL_DB_CACHE)
    return db


def singleton(cls):
    _instance = {}

    def inner():
        if cls not in _instance:
            _instance[cls] = cls()
        return _instance[cls]

    return inner


def test():
    info = get_client().get_account()
    balances = {i['asset']: i['free'] for i in info['balances']}
    logger.debug(balances["BTC"])
    logger.debug(balances["FDUSD"])


if __name__ == '__main__':
    test()
